from flask import Flask, flash, request, redirect, send_file
from werkzeug.utils import secure_filename
import os, subprocess

UPLOAD_FOLDER = '/tmp'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/api/<file_type>',methods=['POST','GET'])
def uploaded_file(file_type):
    if file_type not in ['pdf','html']:
        return 'not support api',404
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'unknow filename', 404
        file = request.files['file']
        if file.filename == '':
            return 'unknow filename', 404
        if file :
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            input_filepath = os.path.join(app.config['UPLOAD_FOLDER'],filename)
            output_filepath = os.path.join(app.config['UPLOAD_FOLDER'],filename.split('.')[0] + '.' + file_type)
            cmd = ['/opt/openoffice4/program/python','/opt/openoffice4/program/DocumentConvert.py',input_filepath,output_filepath]
            try:
                subprocess.check_output(cmd)
            except subprocess.CalledProcessError as e:
                return 'convert errot', 500
            return send_file(output_filepath,as_attachment=True)
    else:
        return '介绍'
